package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;
import com.example.musicplayer.service.InitialService;

import java.util.ArrayList;
import java.util.List;

public class SplashActivity extends ImmersiveActivity {
    private static final String TAG = "SplashActivity";
    private static final int REQUEST_CODE_STORAGE = 1;
    private static final int REQUEST_CODE_NOT_STORAGE = 2;
    //splash页面的持续时间
    private static final int DELAY = 3000;
    private static final int DELAY_SHORT = 1000;
    //有无读写外部存储权限
    private int mAuthority = -1;
    //按钮点击立即进入应用
    private Button mButtonJump;
    private boolean mLoadFinish = false;
    private boolean mNeedLogin = true;

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            startMainActivity();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate(): ");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mButtonJump = findViewById(R.id.activity_splash_button_jump);

        InitialService.setCallBack(new InitialService.SuccessCallBack() {
            @Override
            public void done(boolean needLogin) {
                mLoadFinish = true;
                mNeedLogin = needLogin;
                postDelayed(mRunnable, DELAY);
                mButtonJump.setVisibility(View.VISIBLE);
            }
        });
        mButtonJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeCallbacks(mRunnable);
                startMainActivity();
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !mLoadFinish) {
            getAuthority();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mLoadFinish) {
            postDelayed(mRunnable, DELAY_SHORT);
        }
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause(): ");
        super.onPause();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop(): ");
        super.onStop();
        removeCallbacks(mRunnable);
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
    }

    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        if (mNeedLogin) {
            intent = new Intent(this, LoginActivity.class);
        }
        startActivity(intent);
        this.finish();
        overridePendingTransition(R.anim.normal_left_enter, R.anim.normal_left_exit);
    }

    //获取读写存储的权限并开启音乐服务
    private void getAuthority() {
        checkOverlayPermission();
        List<String> list = new ArrayList<String>();
        int requestCode = REQUEST_CODE_NOT_STORAGE;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            list.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            requestCode = REQUEST_CODE_STORAGE;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) !=
                PackageManager.PERMISSION_GRANTED) {
            list.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (list.size() > 0) {
            String[] permissions = new String[list.size()];
            for (int i = 0; i < permissions.length; i++)
                permissions[i] = list.get(i);
            ActivityCompat.requestPermissions(SplashActivity.this, permissions, requestCode);
        } else {
            mAuthority = 0;
            startService();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                mAuthority = 0;
            } else {
                mAuthority = -1;
            }
        } else {
            mAuthority = 0;
        }
        //请求权限后，启动服务初始化
        startService();
    }

    private void checkOverlayPermission() {
        if (!MusicPlayerApplication.canDrawOverlays() && Build.VERSION.SDK_INT >= 23) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 1);
        }
    }

    //启动应用的初始化服务
    private void startService() {
        Intent intent = new Intent(this, InitialService.class);
        intent.putExtra("authority", mAuthority);
        startService(intent);
    }
}